from fastapi import FastAPI, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from stage2_advanced.chapter05_middleware.config import CORS_CONFIG, GZIP_MIN_SIZE
from stage2_advanced.chapter05_middleware.middleware_examples import (
    SignatureMiddleware, FieldDesensitizeMiddleware, FakeRateLimitMiddleware, ExceptionHandlingMiddleware,
    RequestLogMiddleware, WrapResponseMiddleware
)

app = FastAPI(title="第5章-中间件与请求处理示范", version="1.0.0")

# 统一请求日志中间件
app.add_middleware(RequestLogMiddleware)
# CORS 跨域
app.add_middleware(CORSMiddleware, **CORS_CONFIG)
# GZip 压缩
app.add_middleware(GZipMiddleware, minimum_size=GZIP_MIN_SIZE)
# 响应标准化
app.add_middleware(WrapResponseMiddleware)

app.add_middleware(TrustedHostMiddleware, allowed_hosts=["localhost", "127.0.0.1", ".example.com"])


# app.add_middleware(SignatureMiddleware)
# app.add_middleware(FakeRateLimitMiddleware)
# app.add_middleware(FieldDesensitizeMiddleware)
# app.add_middleware(ExceptionHandlingMiddleware)

@app.get("/ping", summary="健康检查")
async def ping():
    return {"ping": "ok"}


@app.get("/demo", summary="测试接口")
async def demo():
    return {"msg": "Hello Middleware!"}


@app.get("/whoami", summary="返回敏感身份字段，演示脱敏功能")
async def whoami():
    return {
        "user": {
            "name": "张三",
            "phone": "13812345678",
            "email": "hello@fastapi.cn"
        }
    }


@app.get("/error", summary="抛出异常，演示全局捕获")
async def error():
    raise ValueError("模拟程序错误！")


@app.get("/sign-required", summary="测试签名校验中间件")
async def sign():
    return {"secure": True}

# 预留扩展（如 slowapi 限流/test日志/异常测试等）
